package com.hades.xq.miaoshao.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;


/**
 * spring初始化完成之后执行afterPropertiesSet
 */
@Component
public class ValidatorImpl implements InitializingBean {

    private Validator validator;

    public ValidatorResult validator(Object bean) {
        ValidatorResult validatorResult = new ValidatorResult();
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
        if (constraintViolationSet.size() > 0) {
            validatorResult.setHasErrors(true);
            constraintViolationSet.forEach(constraintViolations -> {
                //错误信息
                String errMsg = constraintViolations.getMessage();
                //错误信息对应的字段名称
                String propertyName = constraintViolations.getPropertyPath().toString();
                validatorResult.getErrrMsgMap().put(propertyName, errMsg);
            });
        }
        return validatorResult;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //将hibernate的validator通过工厂的初始化方式使其实例化
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
}
